<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Student List Management</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;

    }

    table,
    th,
    td {
      border: 1px solid rgb(68, 195, 237);
      text-align: center;
    }

    th,
    td {
      padding: 8px;
      /* text-align: left; */
      background-color: #efefef;
    }

    th {
      background-color: #17bebb;
    }


    /* 添加按钮 */
    .openModalBtn {
      background-color: #6ff7f4;
      width: 150px;
      height: 30px;
      border-radius: 5px;
      cursor: pointer;
      border: 0;
    }

    /* 弹框样式 */
    .modal {
      display: none;
      /* 初始隐藏 */
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgb(0, 0, 0);
      background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 300px;
    }

    .modal-content label {
      display: block;
      margin-bottom: 5px;
    }

    .modal-content input[type="text"],
    .modal-content input[type="number"],
    .modal-content select {
      width: 100%;
      padding: 8px;
      margin-bottom: 10px;
      box-sizing: border-box;
      border-radius: 5px;
      border: 1px solid black;
    }

    :is(.modal-content input[type="text"], .modal-content input[type="number"], .modal-content select):focus {
      outline: none;
      border: 1px solid #17bebb;
    }

    .modal-content button {
      width: 100%;
      padding: 10px;
      background-color: #4CAF50;
      color: white;
      border: none;
      cursor: pointer;
    }

    .modal-content button:hover {
      background-color: #45a049;
    }

    .box-top {
      display: flex;
      justify-content: space-between;
      box-sizing: border-box;
      padding: 10px 0;
      height: 50px;
      align-items: center;
    }

    .input-btn {
      border: 1px solid black;
      padding-left: 3px;
      border-radius: 5px;
      height: 30px;
    }

    .inp-set:focus .input-btn {
      border: 2px solid #6ff7f4;
    }

    .inp-set {
      border: 0;
    }

    .inp-set:focus {
      outline: none;
    }

    .btn-set {
      height: 100%;
      width: 60px;
      background-color: #bcc1c0;
      border: 0;
      border-top-right-radius: 5px;
      border-bottom-right-radius: 5px;
      padding: 0;
      cursor: pointer;
    }
  </style>
</head>

<body>

  <h2>Student List Management</h2>
  <div class="box-top">
    <button class="openModalBtn">Add New Student</button>
    <div class="input-btn">
      <input type="text" class="inp-set" placeholder="请输入内容">
      <button class="btn-set">搜索</button>
    </div>
  </div>

  <table class="studentTable">
    <thead>
      <tr>
        <th><input type="checkbox" class="selectAll"></th>
        <th>ID</th>
        <th>Name</th>
        <th>Gender</th>
        <th>Hobbies</th>
        <th>Age</th>
        <th>Iphone</th>
        <th>Eime</th>
        <th>Time</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <!-- Student rows will be added dynamically here -->
    </tbody>
  </table>

  <!-- 添加/修改学生信息的弹框 -->
  <div class="studentModal modal">
    <div class="modal-content">
      <h3 class="modalTitle">Add New Student</h3>
      <form class="studentForm">
        <input type="hidden" class="studentIdToEdit"> <!-- Hidden input to hold ID for editing -->

        <label for="studentName">Name</label>
        <input type="text" name="name" class="studentName" required>

        <label for="studentGender">Gender</label>
        <select name="gender" class="studentGender" required>
          <option value="Male">Male</option>
          <option value="Female">Female</option>
        </select>

        <label for="studentHobbies">Hobbies</label>
        <input type="text" name="hobbies" class="studentHobbies" required>

        <label for="studentAge">Age</label>
        <input type="number" name="age" class="studentAge" required>

        <label for="studentIphone">Iphone <span class="tishi"></span></label>
        <input type="text" name="Iphone" class="studentIphone" required>

        <label for="studentEime">Eime<span class="tishi1"></span></label>
        <input type="text" name="Eime" class="studentEime" required>

        <label for="studentTime">Time<span class="tishi2"></span></label>
        <input type="text" name="Time" class="studentTime" required>

        <button type="submit" class="saveStudentBtn">Save Student</button>
      </form>
    </div>
  </div>

  <script>

    const students = [
      { id: 1, name: 'Alice', gender: 'Female', hobbies: 'Reading', age: 20, Iphone: '192xxxx4532', Eime: '@20588xx372', Time: '2024/02/01 10:10:30' },
      { id: 2, name: 'Bob', gender: 'Male', hobbies: 'Sports', age: 22, Iphone: '192xxxx4532', Eime: '@20588xx372', Time: '2024/02/01 10:14:30' },
      { id: 3, name: 'Charlie', gender: 'Male', hobbies: 'Gaming', age: 21, Iphone: '192xxxx4532', Eime: '@20588xx372', Time: '2024/02/01 10:12:40' }
    ];
    // localStorage.setItem('student', JSON.stringify(students))

    let isEditing = false; // Flag to check if editing

    // 验证手机号
    function shoujihao(shoujih) {
      let reg = /^(?:(?:\+|00)86)?1\d{10}$/
      return reg.test(shoujih)
    }
    function youxianghao(youxiangh) {
      let reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      return reg.test(youxiangh)
    }

    // Function to render the student table
    function renderTable() {
      let shuju = JSON.parse(localStorage.getItem('student')) || []
      console.log(shuju);
      const tbody = document.querySelector('.studentTable tbody');
      tbody.innerHTML = ''; // Clear the table body
      shuju.forEach(student => {
        const row = document.createElement('tr');

        row.innerHTML = `
                    <td><input type="checkbox" class="selectStudent" data-id="${student.id}"></td>
                    <td>${student.id}</td>
                    <td class = 'names'>${student.name}</td>
                    <td>${student.gender}</td>
                    <td>${student.hobbies}</td>
                    <td>${student.age}</td>
                    <td>${student.Iphone}</td>
                    <td>${student.Eime}</td>
                    <td>${student.Time}</td>
                    <td>
                        <button onclick="openEditModal(${student.id})">Edit</button>
                        <button onclick="deleteStudent(${student.id})">Delete</button>
                    </td>
                `;
        tbody.appendChild(row);
      });

    }

    //打开编辑表单模态框  找到对应id 的学生对象
    function openEditModal(id) {

      const student = students.find(s => s.id === id);
      if (student) {
        document.querySelector('.modalTitle').textContent = 'Edit Student';
        document.querySelector('.studentIdToEdit').value = student.id;
        document.querySelector('[name="name"]').value = student.name;
        document.querySelector('[name="gender"]').value = student.gender;
        document.querySelector('[name="hobbies"]').value = student.hobbies;
        document.querySelector('[name="age"]').value = student.age;
        document.querySelector('[name="Iphone"]').value = student.Iphone;
        document.querySelector('[name="Eime"]').value = student.Eime;
        document.querySelector('[name="Time"]').value = student.Time;

        document.querySelector('.studentModal').style.display = 'block';
        //修改表单的 标识
        isEditing = true;


      }
    }

    // Function to handle form submission
    document.querySelector('.studentForm').addEventListener('submit', function (event) {
      event.preventDefault(); // 阻止表单默认提交行为

      const formData = new FormData(this);
      const data = Object.fromEntries(formData.entries());//获取表单提交的数据，格式化对象
      //修改表单 隐藏id
      const id = document.querySelector('.studentIdToEdit').value;

      if (data.name && data.gender && data.hobbies && data.age && data.Iphone && data.Eime && data.Time) {
        // 判断数据是否更新
        if (isEditing) {
          // Update existing student
          const student = students.find(s => s.id === parseInt(id));

          if (student) {
            student.name = data.name;
            student.gender = data.gender;
            student.hobbies = data.hobbies;
            student.age = parseInt(data.age);
            student.Iphone = data.Iphone;
            student.Eime = data.Eime;
            student.Time = data.Time;

          }
          isEditing = false;
        } else {
          //添加一条新数据

          students.push({
            id: students.length ? students[students.length - 1].id + 1 : 1,
            name: data.name,
            gender: data.gender,
            hobbies: data.hobbies,
            age: parseInt(data.age),
            Iphone: data.Iphone,
            Eime: data.Eime,
            Time: data.Time,
          });
        }

        if (!shoujihao(data.Iphone)) {
          alert('手机格式错误')

        }
        if (!youxianghao(data.Eime)) {
          alert('邮箱格式错误')

        }
        //重新渲染数据 
        renderTable();
        // 渲染完成 关闭模态框
        document.querySelector('.studentModal').style.display = 'none';
        clearModal();
      } else {
        alert('请填写完整');
      }
      localStorage.setItem('student', JSON.stringify(students))
    });


    // let span = document.querySelector('.tishi')
    // let span1 = document.querySelector('.tishi1')
    // let span2 = document.querySelector('.tishi2')

    // 清除模态输入的功能 清除表单
    function clearModal() {
      document.querySelector('.studentForm').reset();
      document.querySelector('.studentIdToEdit').value = '';
    }

    // 删除对应学生的数据 
    function deleteStudent(id) {
      const index = students.findIndex(s => s.id === id);
      if (index !== -1) {
        students.splice(index, 1);
        // 删除后重新渲染
        renderTable();
      }
    }

    // 打开模态框 添加新的学生
    document.querySelector('.openModalBtn').addEventListener('click', function () {
      document.querySelector('.modalTitle').textContent = '添加学生';
      document.querySelector('.studentModal').style.display = 'block';
      isEditing = false;
    });

    // 初始化渲染数据到ul
    renderTable();



    // 获取总复选框和所有小复选框
    const selectAllCheckbox = document.querySelector('.selectAll');
    const checkboxes = document.querySelectorAll('.selectStudent');

    // 为总复选框添加事件监听器，当其状态改变时更新所有小复选框的状态
    selectAllCheckbox.addEventListener('click', function () {
      const checkboxes = document.querySelectorAll('.selectStudent');
      checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
      });
    });

    // 为每一个小复选框添加事件监听器，当其状态改变时更新总复选框的状态 
    checkboxes.forEach((checkbox, index, array) => {
      checkbox.addEventListener('click', function () {
        // 检查是否所有小复选框都选中
        const selectAllCheckbox = document.querySelector('.selectAll');
        const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);
        // 如果不是所有小复选框都选中，则取消总复选框的选中状态
        selectAllCheckbox.checked = allChecked;
      });
    });

    // 点击旁白关闭模态框
    window.onclick = function (event) {
      const modal = document.querySelector('.studentModal');
      if (event.target === modal) {
        modal.style.display = 'none';
        clearModal();
        // span.innerHTML = ''
        // span1.innerHTML = ''
        // span2.innerHTML = ''
      }
    };

    // 检索手机号
    // const jinyong = document.querySelector('.saveStudentBtn')
    // jinyong.addEventListener('click', function () {
    //   span.innerHTML = ''
    //   span1.innerHTML = ''
    //   span2.innerHTML = ''
    // })
    // let shoujih = document.querySelector('.studentIphone')
    // shoujih.addEventListener('input', function () {
    //   const ret = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    //   let shouji = ret.test(shoujih.value)
    //   jiansou(shoujih, shouji, span)
    // })

    // //检索邮箱
    // let youxiang = document.querySelector('.studentEime')
    // youxiang.addEventListener('input', function () {
    //   const ret = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    //   let yx = ret.test(youxiang.value)

    //   jiansou(youxiang, yx, span1)
    // })


    // function formatDateTo(date) {
    //   function pad(number) {
    //     return number < 10 ? '0' + number : number;
    //   }

    //   return date.getFullYear() + '-' +
    //     pad(date.getMonth() + 1) + '-' +
    //     pad(date.getDate()) + ' ' +
    //     pad(date.getHours()) + ':' +
    //     pad(date.getMinutes()) + ':' +
    //     pad(date.getSeconds());
    // }
    // const myDate = new Date('2024-08-10 10:12:30');

    // //检索时间
    // let shijian = document.querySelector('.studentTime')
    // shijian.addEventListener('input', function () {
    //   const ret = /^(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)$/
    //   shijian.value = formatDateTo(myDate)
    //   let sj = ret.test(shijian.value)
    //   jiansou(shijian, sj, span2)
    // })

    // function jiansou(js, shouji, span) {
    //   if (!shouji) {
    //     span.innerHTML = '格式错误';
    //     span.style.color = 'red';
    //     // jinyong.disabled = true;
    //   } else {
    //     span.innerHTML = '正确'
    //     span.style.color = 'green'
    //   }
    //   if (js.value === '') {
    //     span.innerHTML = ''
    //   }
    //   s1 = span.textContent === '正确';
    //   s2 = span1.textContent === '正确';
    //   s3 = span2.textContent === '正确';
    //   if (s1 && s2 && s3) {
    //     jinyong.disabled = false
    //   } else {
    //     jinyong.disabled = true
    //   }
    // }

    // 输入框检索name属性
    document.querySelector('.btn-set').addEventListener('click', function () {
      const name = document.querySelectorAll('.names')
      let btninput = document.querySelector('.inp-set').value
      const tbody = document.querySelector('.studentTable tbody');
      tbody.innerHTML = '';

      let found = students.filter(function (item) {
        return item.name.toLowerCase().includes(btninput.toLowerCase());
      });
      // 显示检索结果
      if (found.length > 0) {
        found.forEach(function (item) {
          let resultElement = document.createElement('tr');
          resultElement.innerHTML = `
                    <td><input type="checkbox" class="selectStudent" data-id="${item.id}"></td>
                    <td>${item.id}</td>
                    <td class = 'names'>${item.name}</td>
                    <td>${item.gender}</td>
                    <td>${item.hobbies}</td>
                    <td>${item.age}</td>
                    <td>${item.Iphone}</td>
                    <td>${item.Eime}</td>
                    <td>${item.Time}</td>
                    <td>
                        <button onclick="openEditModal(${item.id})">Edit</button>
                        <button onclick="deleteStudent(${item.id})">Delete</button>
                    </td>
                `;
          tbody.appendChild(resultElement);
        });
      } else {
        renderTable()
      }
    })

    // // 本地存储 
    // function funa() {
    // let shuju = JSON.parse(localStorage.getItem('student')) || []
    // console.log(shuju);
    // const tbody = document.querySelector('.studentTable tbody');
    // tbody.innerHTML = '';
    // shuju.push(students)
    // shuju.forEach(function (item) {
    //   let resultElement = document.createElement('tr');
    //   resultElement.innerHTML = `
    //                 <td><input type="checkbox" class="selectStudent" data-id="${item.id}"></td>
    //                 <td>${item.id}</td>
    //                 <td class = 'names'>${item.name}</td>
    //                 <td>${item.gender}</td>
    //                 <td>${item.hobbies}</td>
    //                 <td>${item.age}</td>
    //                 <td>${item.Iphone}</td>
    //                 <td>${item.Eime}</td>
    //                 <td>${item.Time}</td>
    //                 <td>
    //                     <button onclick="openEditModal(${item.id})">Edit</button>
    //                     <button onclick="deleteStudent(${item.id})">Delete</button>
    //                 </td>
    //             `;
    //   tbody.appendChild(resultElement);
    // });
    // }


    // 0. 搞懂每一行代码 ，打上注释
    // 1. 修正模态框布局样式和整体bug样式，尽量让按钮 Input框美观些（1）提示：盒子模型计算
    // 2. 学生信息增加手机号和邮箱字段列 并在添加和修改的时候验证手机号和邮箱格式-正则
    // 3. 学生信息增加 创建时间和修改时间列 格式【YYYY-MM-DD HH:mm:ss】
    // 4. 列表的右上角增加 input框，搜索按钮，可以使用 name 检索数据，无检索关键词直接点击搜索按钮则默认检索所有数据
    // 5. 讲学生信息存入 localStorage ，使用JSON格式，关闭打开浏览器数据依然在
    // 6. 多选按钮样式和实际选择数据同步（可放最后）




  </script>

</body>

</html>